package com.molihub.listener;

import com.github.pagehelper.PageHelper;
import com.molihub.controller.BaseController;
import com.molihub.controller.SystemController;
import com.molihub.entity.Article;
import com.molihub.entity.ArticleCommentToShow;
import com.molihub.entity.ArticleToShow;
import com.molihub.entity.User;
import com.molihub.utils.LogUtils;
import org.slf4j.Logger;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @ClassName: ApplicationStartListener
 * @Description: TODO
 * @author: GGBOY
 * @date 2020/2/28 19:56
 * @Version: 1.0
 **/
@Component
public class ApplicationStartListener extends BaseController implements CommandLineRunner {
    private static Logger logger = LogUtils.getInstance(ApplicationStartListener.class);
    /**
     * 定义存储显示实体类的容器
     */
    private static List<ArticleToShow> stateToShowList = new ArrayList<>(10);
    private static List<ArticleToShow> articleToShowList = new ArrayList<>(10);

    public static List<ArticleToShow> getStateToShowList() {
        return stateToShowList;
    }

    public static void setStateToShowList(List<ArticleToShow> stateToShowList) {
        ApplicationStartListener.stateToShowList = stateToShowList;
    }

    public static List<ArticleToShow> getArticleToShowList() {
        return articleToShowList;
    }

    public static void setArticleToShowList(List<ArticleToShow> articleToShowList) {
        ApplicationStartListener.articleToShowList = articleToShowList;
    }

    @Override
    public void run(String... args) throws Exception {
        int currentPage = 1;
        // 定义初次刷新显示的文章数 5篇状态，5篇博客
        Integer pageSize = 5;
        // 分页获取数据
        PageHelper.startPage(currentPage, pageSize);
        // 先选取5篇文章进行显示
        List<Article> articles = articleService.getNewestFiveArticle();
        // 分页获取数据
        PageHelper.startPage(currentPage, pageSize);
        // 获取5篇状态
        List<Article> postArticles = articleService.getNewestFivePost();
        // 封装文章信息
        traversalArticleList(articleToShowList, articles);
        // 封装状态信息
        traversalArticleList(articleToShowList, postArticles);
    }

    /**
     * 遍历文章列表，封装对应信息（如评论）到文章显示类实体中
     *
     * @param articleToShows 文章显示实体类列表
     * @param articles       文章列表
     * @author GGBOY
     * @date 2020/2/28
     */
    public void traversalArticleList(List<ArticleToShow> articleToShows, List<Article> articles) {
        for (Article article : articles) {
            // 获取文章的所有评论
            List<ArticleCommentToShow> commentsByArticleId = articleCommentService.getCommentsByArticleId(article.getArticleId());
            logger.info("长度：" + commentsByArticleId.size());
            // 获取评论中的所有一级评论
            List<ArticleCommentToShow> fatherComments = extractFatherComment(commentsByArticleId);
            logger.info("一级评论大小：" + fatherComments.size());
            // 将所有二级评论添加到对应的一级评论中
            extractChildCommentToFatherComment(commentsByArticleId, fatherComments);
            logger.info(fatherComments.toString());
            // 获取对文章点过赞的用户
            List<User> users = articleLikeService.findLikeUsersByArticleId(article.getArticleId());
            ArticleToShow articleToShow = ArticleToShow.builder()
                    .author(userService.getUserById(article.getUserId())).article(article)
                    .likeCount(articleService.getLikeCountByArticle(article.getArticleId()))
                    .commentCount(articleService.getCommentCountByArticle(article.getArticleId())).build();
            articleToShow.setLikeUserList(users);
            articleToShow.setArticleComments(fatherComments);
            articleToShows.add(articleToShow);
        }
    }

    /**
     * 从评论集合中提取一级评论
     *
     * @param commentToShows 评论集合
     * @return java.util.List<com.molihub.entity.ArticleCommentToShow>
     * @author GGBOY
     * @date 2020/2/15
     */
    public List<ArticleCommentToShow> extractFatherComment(List<ArticleCommentToShow> commentToShows) {
        List<ArticleCommentToShow> fatherComments = new ArrayList<>();
        Iterator<ArticleCommentToShow> iterator = commentToShows.iterator();
        while (iterator.hasNext()) {
            // 遍历评论集合，提取一级评论
            ArticleCommentToShow comment = iterator.next();
            logger.info("评论ID:" + comment.getArticleComment().getArticleCommentId());
            if (comment.getArticleComment().getToId() == null) {
                // toId为空表示是一级评论
                fatherComments.add(comment);
                // 将该一级评论从评论集合汇总删除
                iterator.remove();
            }
        }
        logger.info("fatherComments大小：" + fatherComments.size());
        return fatherComments;
    }

    /**
     * 将二级评论添加到对应的一级评论中
     *
     * @param commentToShows 二级评论集合
     * @param fatherComments 一级评论
     * @author GGBOY
     * @date 2020/2/15
     */
    public void extractChildCommentToFatherComment(List<ArticleCommentToShow> commentToShows, List<ArticleCommentToShow> fatherComments) {
        logger.info("二级评论集合大小：" + commentToShows.size() + " 一级评论集合大小：" + fatherComments.size());
        // 遍历父评论集合
        for (ArticleCommentToShow fatherComment : fatherComments) {
            logger.info("一级评论ID: " + fatherComment.getArticleComment().getArticleCommentId());
            // 遍历子评论集合
            for (ArticleCommentToShow chileComment : commentToShows) {
                logger.info("二级评论TOID: " + chileComment.getArticleComment().getToId());
                if (chileComment.getArticleComment().getToId() == fatherComment.getArticleComment().getArticleCommentId()) {
                    // 如果此子评论的to_id为父评论的id，则将该评论添加到父评论的子评论集合中
                    fatherComment.getChildComments().add(chileComment);
                    logger.info("一级评论下的二级评论集合大小：" + fatherComment.getChildComments().size());
                }
            }
        }
    }


}
